package demo3;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 姚东名
 * Date: 2024-05-29
 * Time: 17:42
 */
class Money implements Cloneable {
    public double money = 9.9;

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}
public class Person implements Cloneable {
    public String name;
    public int age;
    //对Money类实例化一个对象：
    public Money m = new Money();
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    /*@Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }*/

    @Override
    protected Object clone() throws CloneNotSupportedException {
        Person tmp = (Person) super.clone();//这个是将person1中的内容拷贝到tmp中，因为Object.Clone(),返回值是Object,所以得强制类型转化
        tmp.m = (Money)this.m.clone();//给成员变量m中的Money再克隆一份，这样就可以做到修改person2，不影响person1
        return tmp;
    }
}
